package com.cxs.service.impl;

import com.cxs.mapper.BookMapper;
import com.cxs.model.Book;
import com.cxs.model.BookExample;
import com.cxs.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cxs.utils.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/9/30  22:04
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Override
    public PageInfo<Book> listByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Book> bookList = bookMapper.selectByExample(null);
        PageInfo<Book> pageInfo = new PageInfo<Book>(bookList);
        return pageInfo;
    }

    @Override
    public PageInfo<Book> listByPageAndCid(Integer pageNum, Integer pageSize,Integer cid) {
        PageHelper.startPage(pageNum, pageSize);
        BookExample bookExample = new BookExample();
        BookExample.Criteria criteria = bookExample.createCriteria();
        criteria.andCategoryIdEqualTo(cid);
        List<Book> bookList = bookMapper.selectByExample(bookExample);
        PageInfo<Book> pageInfo = new PageInfo<Book>(bookList);
        return pageInfo;
    }

    @Override
    public Result delete(Integer id) {
        return bookMapper.deleteByPrimaryKey(id) > 0 ? Result.OK("删除成功!") : Result.failare("删除失败");
    }

    @Override
    public Result add(Book book) {
        return bookMapper.insert(book) > 0 ? Result.OK("添加成功!") : Result.failare("添加失败");
    }

    @Override
    public Result getOne(Integer id) {
        Book book = bookMapper.selectByPrimaryKey(id);
        if(book != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            book.setReqDate(sdf.format(book.getCreatedate()));
            return Result.OK("OK",book);
        }
        return Result.failare("失败");
    }

    @Override
    public Result update(Book book) {
        return bookMapper.updateByPrimaryKey(book) > 0 ? Result.OK("修改成功!") : Result.failare("修改失败");
    }
}
